package com.example.Controller;

import com.alibaba.fastjson.JSON;
import com.example.Req.LotteryTicketReq;
import com.example.common.BizException;
import com.example.common.Pagination;
import com.example.common.ResponseModel;
import com.example.model.LotteryTicket;
import com.example.model.LotteryTicketRes;
import com.example.service.MongoLotteryTicketService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

@RestController
@Slf4j
public class MongoLetteryTicketController {
    @Autowired
    private MongoLotteryTicketService mongoLotteryTicketService;
    public static List<String> animalList = new ArrayList<String>() {{
        add("鼠");
        add("牛");
        add("虎");
        add("兔");
        add("龙");
        add("蛇");
        add("马");
        add("羊");
        add("猴");
        add("鸡");
        add("狗");
        add("猪");
    }};
    private static Set<String> animalSet = new HashSet<String>() {{
        add("鼠");
        add("牛");
        add("虎");
        add("兔");
        add("龙");
        add("蛇");
        add("马");
        add("羊");
        add("猴");
        add("鸡");
        add("狗");
        add("猪");
    }};

    private final String SEPARTOR = ",";

    @PostMapping("/api/qibuzhong/insertOrUpdateData.do")
    public ResponseModel<String> insertOrUpdateData(@RequestBody LotteryTicketReq req) throws Exception{
        log.info("insertNewData:{}", JSON.toJSONString(req));
        if(req ==  null || StringUtils.isBlank(req.getContent())
                || StringUtils.isBlank(req.getNo())  || req.getType() == null
                || req.getSerialNo() == null){
            log.error("insertNewData param is null");
            throw new BizException("00000001", "参数错误");
        }
        String content = req.getContent().replaceAll(":", ",")
                .replaceAll("：", ",")
                .replaceAll("，", ",");
        req.setContent(content);
        if(req.getId() != null){
            mongoLotteryTicketService.updateLotteryTicket(req);
        }else{
            mongoLotteryTicketService.insertLotteryTicket(req);
        }
        return new ResponseModel<>();
    }

    @RequestMapping("/api/qibuzhong/deleteData.do")
    public ResponseModel<String> deleteData(@RequestBody LotteryTicketReq req) throws Exception{
        log.info("insertNewData:{}", JSON.toJSONString(req));
        if(req ==  null || req.getId() == null  || req.getType() == null ){
            log.error("insertNewData param is null");
            throw new BizException("00000001", "参数错误");
        }

        mongoLotteryTicketService.delLotteryTicket(req);
        return new ResponseModel<>();
    }

    @RequestMapping("/api/qibuzhong/getTicketListPage.do")
    public ResponseModel<Pagination<LotteryTicketRes>> getTicketListPage(@RequestBody LotteryTicketReq req){
        if(req == null || req.getType() == null || req.getType()==null){
            throw new BizException("00000001", "参数错误");
        }
        ResponseModel<Pagination<LotteryTicketRes>> result = new ResponseModel<>();
        log.info("getRepeatListPage param:{}", JSON.toJSONString(req));
        if (req.getPageNo() == null) {
            req.setPageNo(1);
        }
        if (req.getPageSize() == null) {
            req.setPageSize(50);
        }

        if(StringUtils.isBlank(req.getNo())){
            req.setNo(null);
        }else{
            String content = req.getNo().replaceAll(":", ",")
                    .replaceAll("：", ",")
                    .replaceAll("#", ",")
                    .replaceAll("，", ",");
            req.setNo(content);
        }


        Pagination<LotteryTicketRes> pagination = mongoLotteryTicketService.getTicketListPage(req);
        log.info("getRepeatList size:{}", pagination.getList().size());
        result.setData(pagination);
        return result;
    }

    @RequestMapping("/api/qibuzhong/getBuyTicketList.do")
    public ResponseModel<List<LotteryTicketRes>> getBuyTicketList(@RequestBody LotteryTicketReq req){
        ResponseModel<List<LotteryTicketRes>> responseModel = new ResponseModel<>();
        if(req == null || req.getType() == null ){
            throw new BizException("00000001", "参数错误");
        }
/*        if(req == null){
            req = new  LotteryTicketReq();
            req.setRepeat(4l);
        }
        if(req.getRepeat() == null && req.getType()<3){
            req.setRepeat(4l);
        }
        if(req.getRepeat() == null && req.getType()>=3){
            req.setRepeat(4l);
        }*/
        List<LotteryTicketRes> list = mongoLotteryTicketService.getBuyTicketList(req);
        responseModel.setData(list);
        return responseModel;
    }

    @PostMapping("/api/qibuzhong/autoInsertAnimal.do")
    public ResponseModel<String> autoInsertAnimal(@RequestBody LotteryTicketReq req){
        if(req == null || req.getType()==null){
            log.error("autoInsertAnimal param is null");
            throw new BizException("00000001", "参数错误");
        }
        //animalList.get();
        Random random = new Random();
        int a;
        for(int i = 0; i < 1000; i++){
            a = random.nextInt(12)+1;
        }
        long No = 1;
        while(true){
            if(No == 1001){
                break;
            }
            LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
            for(int i = 0; i < 3; i++){
                a = random.nextInt(12)+1;
            }
            while(true){
                if(set.size() == 6){
                    break;
                }
                a = random.nextInt(12)+1;
                set.add(a);
            }
            // 使用
            Iterator<Integer> iterator = set.iterator();
            StringBuilder contentBuilder = new StringBuilder();
            while(iterator.hasNext()){
                int index = iterator.next();
                String animal = animalList.get(index-1);
                contentBuilder.append(animal);
                contentBuilder.append(",");
            }
            contentBuilder.deleteCharAt(contentBuilder.length()-1);
            String content = contentBuilder.toString();
            log.info(content);

            req.setNo(String.valueOf(No));
            req.setContent(content);
            req.setSerialNo(No);
            try {
                insertOrUpdateData(req);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //清除set
            set.clear();
            No = No+1;
        }

        return new ResponseModel<>();
    }

    @PostMapping("/api/qibuzhong/autoInsertNumberEnd.do")
    public ResponseModel<String> autoInsertNumberEnd(@RequestBody LotteryTicketReq req){
        if(req == null || req.getType()==null){
            log.error("autoInsertNumberEnd param is null");
            throw new BizException("00000001", "参数错误");
        }
        //animalList.get();
        Random random = new Random();
        int a = 1;
        for(int i = 0; i< 100; i++){
            a = random.nextInt(10);
        }
        long No = 1;
        while(true){
            if(No == 1001){
                break;
            }
            for(int i = 0; i< 1; i++){
                a = random.nextInt(10);
            }
            // 使用
            StringBuilder contentBuilder = new StringBuilder();
            for(int i = 0; i <= 4; i++) {
                if(a == 0 && i == 0){
                    continue;
                }
                contentBuilder.append(i);
                contentBuilder.append(a);
                contentBuilder.append(",");
            }
            contentBuilder.deleteCharAt(contentBuilder.length()-1);
            String content = contentBuilder.toString();
            log.info(content);

            req.setNo(String.valueOf(No));
            req.setContent(content);
            req.setSerialNo(No);
            try {
                insertOrUpdateData(req);
            } catch (Exception e) {
                e.printStackTrace();
            }
            No = No+1;
        }
        return new ResponseModel<>();
    }

    public static void main(String[] args){
        Random random = new Random();
        int a;
        for(int i = 0; i < 1000; i++){
            a = random.nextInt(12)+1;
        }
        int No = 1;
        while(true){
            if(No == 10001){
                break;
            }
            LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
            for(int i = 0; i < 20; i++){
                a = random.nextInt(12)+1;
            }
            while(true){
                if(set.size() == 6){
                    break;
                }
                a = random.nextInt(12)+1;
                set.add(a);
            }
            // 使用
            Iterator<Integer> iterator = set.iterator();
            StringBuilder contentBuilder = new StringBuilder();
            while(iterator.hasNext()){
                int index = iterator.next();
                String animal = animalList.get(index-1);
                contentBuilder.append(animal);
                contentBuilder.append(",");
            }
            contentBuilder.deleteCharAt(contentBuilder.length()-1);
            System.out.println(contentBuilder.toString());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //清除set
            set.clear();
            No = No+1;
        }

        //animalList.get(0)
    }

    @RequestMapping("/api/qibuzhong/addNumList.do")
    public ResponseModel<String> addNumList(@RequestParam("type") Integer type, @RequestParam("startNo")Long startNo){
        if(type == null){
            throw new BizException("00000001", "参数错误");
        }
        List<LotteryTicketReq> datas = new ArrayList<>();
        batchInsertLotteryTicket(15,  type, datas);
        for(LotteryTicketReq lotteryTicketReq: datas){
            lotteryTicketReq.setNo(String.valueOf(startNo));
            lotteryTicketReq.setSerialNo(startNo);
            mongoLotteryTicketService.insertLotteryTicket(lotteryTicketReq);

            startNo++;
        }
        return new ResponseModel<>();
    }
    @RequestMapping("/api/qibuzhong/addAnimalList.do")
    public ResponseModel<String> addAnimalList(@RequestParam("type") Integer type, @RequestParam("startNo")Long startNo){
        if(type == null){
            throw new BizException("00000001", "参数错误");
        }
        List<LotteryTicketReq> datas = new ArrayList<>();
        batchInsertLotteryTicketAnimal(15,  type, datas);
        for(LotteryTicketReq lotteryTicketReq: datas){
            lotteryTicketReq.setNo(String.valueOf(startNo));
            lotteryTicketReq.setSerialNo(startNo);
            mongoLotteryTicketService.insertLotteryTicket(lotteryTicketReq);

            startNo++;
        }
        return new ResponseModel<>();
    }


    public void batchInsertLotteryTicket(int year, int type, List<LotteryTicketReq> lotteryTickets) {
        try {
            String url = "https://kjh.55128.cn/hk6-history-";
            if(type > 1000){
                //url = "https://kjh.55128.cn/am6hc-history-";
                url = "https://kjh.55128.cn/newam6hc-history-";
            }
            //URL url = new URL("https://kjh.55128.cn/hk6-history-2022.htm");
            //Document document = Jsoup.parse(url, 100000);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> result = restTemplate.getForEntity(url + year + ".htm", String.class);
            String str = result.getBody();
            Document document = Jsoup.parse(str);

            Elements element = document.getElementsByTag("body");
            Elements mainElements = element.first().getElementsByClass("main");
            //log.info(mainElements.html());

            Elements div = mainElements.first().getElementsByClass("detail-wrapper");
            Element divTable = document.getElementById("table");
            Element table = divTable.getElementsByTag("table").first();
            // 解析thead标签以及下面的th ,去掉多余的th 标签
            Element theadTr = table.getElementsByTag("thead").first()
                    .getElementsByTag("tr").first();
            Elements theadTrTh = theadTr.getElementsByTag("th");
            theadTrTh.remove(7);
            theadTrTh.remove(6);
            theadTrTh.remove(5);
            theadTrTh.remove(4);
            theadTrTh.remove(3);
            theadTr.empty();
            for (Element th : theadTrTh) {
                theadTr.append(th.toString());
            }
            log.info(theadTr.html());

            Element tbodyElement = table.getElementsByTag("tbody").first();

            // 解析 tbody 标签 以及下面的
            Elements tBodyTrList = table.getElementsByTag("tbody").first()
                    .getElementsByTag("tr");
            //List<LotteryTicketReq> lotteryTickets = new ArrayList<>();
            for (Element tBodyTr : tBodyTrList) {
                Elements tBodyTrTdList = tBodyTr.getElementsByTag("td");
                tBodyTrTdList.remove(8);
                tBodyTrTdList.remove(7);
                tBodyTrTdList.remove(6);
                tBodyTrTdList.remove(5);
                tBodyTrTdList.remove(4);
                tBodyTrTdList.remove(3);
                tBodyTr.empty();
                // 遍历td
                for (Element td : tBodyTrTdList) {
                    log.info(td.html().trim());
                    tBodyTr.append(td.toString());
                }
                // 买🐎 对象
                LotteryTicketReq lotteryTicket = new LotteryTicketReq();

                Element dateElement = tBodyTrTdList.get(0); // 开奖日期
                //lotteryTicket.setPublishDate(dateElement.html().trim());

                Element noElement = tBodyTrTdList.get(1);   // 开奖期数
                lotteryTicket.setNo(noElement.html().trim());

                Element numberModuleElement = tBodyTrTdList.get(2);   // 开奖号码模块
                Elements divElementList = numberModuleElement.getElementsByTag("div");

                Element numberDivElement = divElementList.get(0);  // 号码
                Elements numberDivSpanElements = numberDivElement.getElementsByTag("span");
                //List<TicketContent> ticketContents = new ArrayList<>();
                List<String> contentList = new ArrayList<>();
                //List<String> colorList = new ArrayList<>();
                for (Element numberDivSpan : numberDivSpanElements) {
                    /*Set<String> spanClassNames = numberDivSpan.classNames();
                    if (spanClassNames.contains("gray")) {
                        continue;
                    }
                    spanClassNames.retainAll(colorSet);
                    TicketContent ticketContent = new TicketContent();
                    ticketContent.setColor(spanClassNames.iterator().next()); // 颜色
                    ticketContent.setContent(numberDivSpan.html().trim()); //号码

                    contentList.add(ticketContent.getContent());
                    colorList.add(ticketContent.getColor());
                    ticketContents.add(ticketContent);*/

                    String numberStr = numberDivSpan.html().trim();
                    if("+".equals(numberStr)){
                        continue;
                    }
                    int a = Integer.parseInt(numberStr);
                    numberStr = a<10? ("0"+a):(a+"");

                    contentList.add(numberStr);
                }
                //log.info("ticketContents:{}", JSON.toJSONString(ticketContents));
                lotteryTicket.setContent(String.join(SEPARTOR, contentList));
                //lotteryTicket.setColor(String.join(SEPARTOR, colorList));
                lotteryTicket.setType(type);
                //lotteryTicket.setTableIndex(type%2);
                /*Element animalDivElement = divElementList.get(1);  // 生肖
                List<String> animalList = new ArrayList<>();
                Elements animalDivSpanElements = animalDivElement.getElementsByTag("span");
                for (Element animalDivSpan : animalDivSpanElements) {
                    String a = animalDivSpan.html().trim();
                    if (animalSet.contains(a)) {
                        animalList.add(a);
                    }
                }
                log.info("animalList:{}", JSON.toJSONString(animalList));
                lotteryTicket.setAnimalList(animalList);
                lotteryTicket.setAnimal(String.join(SEPARTOR, animalList));

                Element wuxingDivElement = divElementList.get(2);  // 五行
                Elements wuxingDivSpanElements = wuxingDivElement.getElementsByTag("span");
                List<String> wuxingList = new ArrayList<>();
                for (Element wuxingDivSpan : wuxingDivSpanElements) {
                    String a = wuxingDivSpan.html().trim();
                    if (wuxingSet.contains(wuxingDivSpan.html().trim())) {
                        wuxingList.add(a);
                        ;
                    }
                }
                log.info("wuxingList:{}", JSON.toJSONString(wuxingList));
                lotteryTicket.setWuxingList(wuxingList);
                lotteryTicket.setWuxing(String.join(SEPARTOR, wuxingList));
*/
                lotteryTickets.add(lotteryTicket);
            }
            log.info("tbodyElement:{}", tbodyElement.html());
            log.info("lotteryTicketList:{}", JSON.toJSONString(lotteryTickets));
            if (CollectionUtils.isEmpty(lotteryTickets)) {
                return ;
            }
            lotteryTickets.sort(new Comparator<LotteryTicketReq>() {
                @Override
                public int compare(LotteryTicketReq o1, LotteryTicketReq o2) {
                    return Integer.parseInt(o1.getNo()) - Integer.parseInt(o2.getNo());
                }
            });
            //lotteryTicketMapper.batchInsertLotteryTicket("fcap_lottery_ticket"+type,lotteryTickets);
            //lotteryTicketMapper.batchUpdateSerialNo("fcap_lottery_ticket"+type, type);
            log.info("==================================");


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void batchInsertLotteryTicketAnimal(int year, int type, List<LotteryTicketReq> lotteryTickets) {
        try {
            String url = "https://kjh.55128.cn/hk6-history-";
            if(type > 1000){
                //url = "https://kjh.55128.cn/am6hc-history-";
                url = "https://kjh.55128.cn/newam6hc-history-";
            }
            //URL url = new URL("https://kjh.55128.cn/hk6-history-2022.htm");
            //Document document = Jsoup.parse(url, 100000);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> result = restTemplate.getForEntity(url + year + ".htm", String.class);
            String str = result.getBody();
            Document document = Jsoup.parse(str);

            Elements element = document.getElementsByTag("body");
            Elements mainElements = element.first().getElementsByClass("main");
            //log.info(mainElements.html());

            Elements div = mainElements.first().getElementsByClass("detail-wrapper");
            Element divTable = document.getElementById("table");
            Element table = divTable.getElementsByTag("table").first();
            // 解析thead标签以及下面的th ,去掉多余的th 标签
            Element theadTr = table.getElementsByTag("thead").first()
                    .getElementsByTag("tr").first();
            Elements theadTrTh = theadTr.getElementsByTag("th");
            theadTrTh.remove(7);
            theadTrTh.remove(6);
            theadTrTh.remove(5);
            theadTrTh.remove(4);
            theadTrTh.remove(3);
            theadTr.empty();
            for (Element th : theadTrTh) {
                theadTr.append(th.toString());
            }
            log.info(theadTr.html());

            Element tbodyElement = table.getElementsByTag("tbody").first();

            // 解析 tbody 标签 以及下面的
            Elements tBodyTrList = table.getElementsByTag("tbody").first()
                    .getElementsByTag("tr");
            //List<LotteryTicketReq> lotteryTickets = new ArrayList<>();
            for (Element tBodyTr : tBodyTrList) {
                Elements tBodyTrTdList = tBodyTr.getElementsByTag("td");
                tBodyTrTdList.remove(8);
                tBodyTrTdList.remove(7);
                tBodyTrTdList.remove(6);
                tBodyTrTdList.remove(5);
                tBodyTrTdList.remove(4);
                tBodyTrTdList.remove(3);
                tBodyTr.empty();
                // 遍历td
                for (Element td : tBodyTrTdList) {
                    log.info(td.html().trim());
                    tBodyTr.append(td.toString());
                }
                // 买🐎 对象
                LotteryTicketReq lotteryTicket = new LotteryTicketReq();

                Element dateElement = tBodyTrTdList.get(0); // 开奖日期
                //lotteryTicket.setPublishDate(dateElement.html().trim());

                Element noElement = tBodyTrTdList.get(1);   // 开奖期数
                lotteryTicket.setNo(noElement.html().trim());

                Element numberModuleElement = tBodyTrTdList.get(2);   // 开奖号码模块
                Elements divElementList = numberModuleElement.getElementsByTag("div");

                //Element numberDivElement = divElementList.get(0);  // 号码
                //Elements numberDivSpanElements = numberDivElement.getElementsByTag("span");
                //List<TicketContent> ticketContents = new ArrayList<>();
                //List<String> contentList = new ArrayList<>();
                //List<String> colorList = new ArrayList<>();
                /*for (Element numberDivSpan : numberDivSpanElements) {
                    Set<String> spanClassNames = numberDivSpan.classNames();
                    if (spanClassNames.contains("gray")) {
                        continue;
                    }
                    spanClassNames.retainAll(colorSet);
                    TicketContent ticketContent = new TicketContent();
                    ticketContent.setColor(spanClassNames.iterator().next()); // 颜色
                    ticketContent.setContent(numberDivSpan.html().trim()); //号码

                    contentList.add(ticketContent.getContent());
                    colorList.add(ticketContent.getColor());
                    ticketContents.add(ticketContent);

                    String numberStr = numberDivSpan.html().trim();
                    if("+".equals(numberStr)){
                        continue;
                    }
                    int a = Integer.parseInt(numberStr);
                    numberStr = a<10? ("0"+a):(a+"");

                    contentList.add(numberStr);
                }*/
                //log.info("ticketContents:{}", JSON.toJSONString(ticketContents));
                //lotteryTicket.setContent(String.join(SEPARTOR, contentList));
                //lotteryTicket.setColor(String.join(SEPARTOR, colorList));
                lotteryTicket.setType(type);
                //lotteryTicket.setTableIndex(type%2);
                Element animalDivElement = divElementList.get(1);  // 生肖
                List<String> animalList = new ArrayList<>();
                Elements animalDivSpanElements = animalDivElement.getElementsByTag("span");
                for (Element animalDivSpan : animalDivSpanElements) {
                    String a = animalDivSpan.html().trim();
                    if (animalSet.contains(a)) {
                        animalList.add(a);
                    }
                }
                log.info("animalList:{}", JSON.toJSONString(animalList));
                lotteryTicket.setAnimalList(animalList);
                //lotteryTicket.setAnimal(String.join(SEPARTOR, animalList));
                lotteryTicket.setContent(animalList.get(animalList.size()-1));
                /*Element wuxingDivElement = divElementList.get(2);  // 五行
                Elements wuxingDivSpanElements = wuxingDivElement.getElementsByTag("span");
                List<String> wuxingList = new ArrayList<>();
                for (Element wuxingDivSpan : wuxingDivSpanElements) {
                    String a = wuxingDivSpan.html().trim();
                    if (wuxingSet.contains(wuxingDivSpan.html().trim())) {
                        wuxingList.add(a);
                        ;
                    }
                }
                log.info("wuxingList:{}", JSON.toJSONString(wuxingList));
                lotteryTicket.setWuxingList(wuxingList);
                lotteryTicket.setWuxing(String.join(SEPARTOR, wuxingList));
*/
                lotteryTickets.add(lotteryTicket);
            }
            log.info("tbodyElement:{}", tbodyElement.html());
            log.info("lotteryTicketList:{}", JSON.toJSONString(lotteryTickets));
            if (CollectionUtils.isEmpty(lotteryTickets)) {
                return ;
            }
            lotteryTickets.sort(new Comparator<LotteryTicketReq>() {
                @Override
                public int compare(LotteryTicketReq o1, LotteryTicketReq o2) {
                    return Integer.parseInt(o1.getNo()) - Integer.parseInt(o2.getNo());
                }
            });
            log.info("==================================");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
